<script setup>
import { ref, watch, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { chartColors } from '@/config/colors'
import { curveAPI } from '@/services/api'
import { useCurveStore } from '@/stores/curveStore'
import { useExperimentStore } from '@/stores/experiment'
import CurveSettings from '@/components/CurveSettings.vue'
import { ChartManager, ChartGesture } from '@/utils/chartManager'

const route = useRoute()
const curveStore = useCurveStore()
const experimentStore = useExperimentStore()
const loading = ref(false)
const activeTab = ref('settings')
const chartInstance = ref(null)
const chartGesture = ref(null)
const savingImage = ref(false)


// 使用本地设置，初始化默认值
const localSettings = ref({
  experimentId: '',
  experimentName: '',
  timeRange: {
    start: '',
    end: ''
  },
  channels: [
    {
      id: 1,
      experimentId: '',
      channel: '',
      transform: '',
      unit: '',
      position: '1',
      color: chartColors[0],
      enabled: true
    }
  ]
})


// 只在路由参数变化时更新设置
watch(() => route.params.settings, (newSettings) => {
  if (newSettings === 'template') {
    try {
      const templateSettings = curveStore.settings;
      localSettings.value = { ...templateSettings };
    } catch (error) {
      console.error('Template settings parse error:', error)
      ElMessage.error('模板设置解析失败')
    }
  }
}, { immediate: true })

const handleSettingsUpdate = (newSettings) => {
  localSettings.value = newSettings
}

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance.value) {
    chartInstance.value.resize()
  }
}

const drawCurve = async () => {
  if (!localSettings.value.experimentId || !localSettings.value.channels?.length) {
    ElMessage.warning('请先选择实验和通道')
    return
  }

  loading.value = true
  try {
    const response = await curveAPI.getCurveData({
      experimentId: localSettings.value.experimentId,
      channels: localSettings.value.channels,
      timeRange: localSettings.value.timeRange
    })

    // 保存原始数据
    curveStore.setOriginalData(response.data.data)
    experimentStore.setCurrentExperiment(response.data.experiment)
    
    activeTab.value = 'preview'
    await nextTick()
    
    initChart(response.data.data)
  } catch (error) {
    console.error('Draw curve error:', error)
    ElMessage.error(error.response?.data?.error || '获取数据失败')
  } finally {
    loading.value = false
  }
}

const initChart = (data) => {
  const chartDom = document.getElementById('permanent-chart')
  if (chartDom) {
    if (chartInstance.value) {
      chartInstance.value.dispose()
    }
    
    chartInstance.value = echarts.init(chartDom)
    const option = ChartManager.generateOption(data)
    chartInstance.value.setOption(option)
    
    if (chartGesture.value) {
      chartGesture.value.destroy()
    }
    chartGesture.value = new ChartGesture(chartInstance.value, data, localSettings.value)
  }
}

const saveChartImage = async () => {
  if (!chartInstance.value) return
  
  try {
    savingImage.value = true
    
    // 获取图表的 base64 图片数据
    const base64Data = chartInstance.value.getDataURL({
      type: 'png',
      pixelRatio: 2,
      backgroundColor: '#fff'
    })

    // 只需要发送图片数据和实验ID
    await curveAPI.saveChartImage({
      imageData: base64Data,
      experimentId: localSettings.value.experimentId
    })

    ElMessage.success('图片已保存到日志')
  } catch (error) {
    console.error('保存图片失败:', error)
    ElMessage.error('保存图片失败: ' + error.message)
  } finally {
    savingImage.value = false
  }
}

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (chartInstance.value) {
    chartInstance.value.dispose()
    chartInstance.value = null
  }
  if (chartGesture.value) {
    chartGesture.value.destroy()
  }
})
</script>

<template>
  <div class="curve-view" v-loading="loading" element-loading-text="加载中...">
    <div class="tab-header">
      <el-radio-group v-model="activeTab">
        <el-radio-button value="settings">设置</el-radio-button>
        <el-radio-button value="preview">预览</el-radio-button>
        <el-button 
          v-if="activeTab === 'preview'" 
          type="primary" 
          @click="saveChartImage"
          :loading="savingImage"
          style="margin-left: 16px"
        >
          保存图片到日志
        </el-button>
      </el-radio-group>
    </div>

    <div v-show="activeTab === 'settings'" class="settings-pane">
      <CurveSettings 
        :settings="localSettings" 
        @update:settings="handleSettingsUpdate"
        @draw-curve="drawCurve" 
      />
    </div>

    <div v-show="activeTab === 'preview'" class="preview-container">
      <div class="chart-wrapper">
        <div id="permanent-chart" class="permanent-chart"></div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.curve-view {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 5px;
  box-sizing: border-box;
}

.tab-header {
  margin-bottom: 5px;
}

.settings-pane {
  flex: 1;
}

.preview-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.chart-wrapper {
  flex: 1;
  min-height: 500px;
  position: relative;
  border: 1px solid #dcdfe6;
  background: #fff;
  padding: 5px;
  border-radius: 4px;
}

.permanent-chart {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
</style>